# !/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import pymongo

from base.connection import mongodb_util, get_db_session

logger = logging.getLogger(__name__)


# 获取设备信息
def get_device(openid):
    """
    获取设备信息
    :param openid:
    :return:
    """
    openid = str(openid)
    try:

        db = mongodb_util.db
        device = None
        # 查找当前绑定一台的设备
        d = db.devices_users.find({"openid": openid, "active": 1, "current_bind": 1}).sort([('updatetime', -1)]).limit(
            1)
        if d.count() > 0:
            for i in d:
                device = i
        else:
            d = db.devices_users.find({"openid": openid, "active": 1}).sort([('updatetime', -1)]).limit(1)
            for i in d:
                db.devices_users.update({"openid": openid, "active": 1, 'did': i['did']},
                                        {'$set': {"current_bind": 1}})
                device = i
        db.logout()
        return device
    except Exception as e:
        logger.exception(e)
        return None


def get_device_list(open_id):
    """
    获取用户绑定的设备编号列表
    :param open_id:
    :return:
    """
    # 查询用户所扫过绑定的设备编号
    try:
        class Device(object):
            pass

        session = get_db_session([
            {"db_table": "ebt_device", "model": Device}
        ])
        device_list = []
        db = mongodb_util.db
        devices = db.devices_users.find({"openid": open_id}).sort("updatetime", pymongo.DESCENDING)
        for device in devices:
            device_id = device.get("did", None)

            if not device_id:
                continue

            d = session.query(Device).filter_by(ebf_device_id=device_id, ebf_device_is_online=1).first()
            if d:
                device_list.append(device_id)
        return device_list
    except Exception as e:
        logger.exception(e)
        return []


def get_owner_devices(open_id):
    """
    获取用户所拥有的设备列表
    :param open_id:
    :return:
    """
    try:
        device_list = []
        db = mongodb_util.db
        devices = db.devices.find({"master": open_id}).sort("_updated", pymongo.DESCENDING)
        for device in devices:
            device_id = device.get("_id")
            device_list.append(device_id)
        return device_list
    except Exception as e:
        logger.exception(e)
        return []


def is_owner_device(device_id, open_id):
    """
    判断用户是不是设备主人
    :param device_id:
    :param open_id:
    :return:
    """
    try:
        db = mongodb_util.db
        device = db.devices.find({"master": open_id, "_id": device_id})
        if device.count():
            return True
        return False
    except Exception as e:
        logger.exception(e)
        return False